<?php
namespace App\Http\Controllers\ShopWeb;

use App\Http\Controllers\WebController;
use App\Http\Controllers\Business\ShopWeb\PublicBusiness;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Auth;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class QrcodeController extends WebController
{
	//专属二维码
    public function shopQrcode() {
        if(Cookie::has('shopids')) {
            $shopIdString = Cookie::get('shopids');
        } else {
            $shopUser = Auth::guard('shopweb')->user();
            $shopIdString = $shopUser->shopid;
        }
        $shopIdArray = explode(',', $shopIdString);
        $lists = [];
        foreach($shopIdArray as $shopId) {
            $result = PublicBusiness::getShopDetailByShopId($shopId);
            if($result['status'] == 'success') {
                $shop = $result['data'];
                array_push($lists, [
                    'shopid' => $shopId,
                    'shopname' => $shop['name'],
                    'address' => $shop['address']
                ]);
            }
        }
        $data = [
            'lists' => $lists,
            'count' => count($lists)
        ];
        return view('shop.qrcode.shop_qrcode', $data);
    }
    //下载二维码
    public function downloadShopQrcode() {
        $shopId = $this->request->get('shopid');
        if(!$shopId) {
            return $this->responseError('参数错误');
        }
        $file = '../storage/qrcode/' . $shopId . '.png';
        $url = env('WEB_URL') . "qrcode/shop/".$shopId;
        $qrc1 = QrCode::format('png')->size(200)->margin(0)->generate($url);
        if (!file_exists($file)) {
            $myFile = fopen($file, 'a+');
        } else {
            $myFile = fopen($file, 'a+');
        }
        fwrite($myFile, $qrc1);
        fclose($myFile);
        return response()->download($file)->deleteFileAfterSend(true);
    }
}